package com.cis467.mrball;

import com.cis467.mrball.backend.GameManagement;
import com.cis467.mrball.backend.LocalContent;
import com.cis467.mrball.parts.Level;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.Toast;

public class BuildLevel extends Activity implements OnTouchListener{

	private static final int MENU_NEW = 0;

	private static final int MENU_LOAD = 1;

	private static final int MENU_SAVE = 2;

	private static final int MENU_UPLOAD = 3;

	private static final int MENU_TEST = 4;

	private static final int MENU_HELP = 5;

	/** A handle to the View in which the game is running. */
	private BuildLevelView mBuildLevelView;


	/**
	 * Invoked during init to give the Activity a chance to set up its Menu.
	 * 
	 * @param menu the Menu to which entries may be added
	 * @return true
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, MENU_NEW, 0, "New");
		menu.add(0, MENU_LOAD, 0, "Load");
		menu.add(0, MENU_SAVE, 0, "Save");
		menu.add(0, MENU_UPLOAD, 0, "Upload");
		menu.add(0, MENU_TEST, 0, "Test");
		menu.add(0, MENU_HELP, 0, "Help");

		return true;
	}

	/**
	 * Invoked when the user selects an item from the Menu.
	 * 
	 * @param item the Menu entry which was selected
	 * @return true if the Menu item was legit (and we consumed it), false
	 *         otherwise
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case MENU_NEW:
			// Do you want to save? 
			mBuildLevelView.newLevel();
			//	mBuildLevelView.loadLevel(new Level());
			return true;

		case MENU_LOAD:
			// Do you want to save?

			launchLevelSelect();

			return true;

		case MENU_SAVE:

			saveLevel();

			return true;

		case MENU_UPLOAD:
			uploadLeveL();
			return true;  

		case MENU_TEST:

			launchTest();

			return true;

		case MENU_HELP:
			// Popup dialog with description
		}

		return false;
	}



	/**
	 * Invoked when the Activity is created.
	 * 
	 * @param savedInstanceState a Bundle containing state saved from a previous
	 *        execution, or null if this is a new execution
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// tell system to use the layout defined in our XML file
		setContentView(R.layout.buildlevel_layout);

		// get handles to view
		mBuildLevelView = (BuildLevelView) findViewById(R.id.buildlevel);

		mBuildLevelView.requestFocus();

		mBuildLevelView.setFocusableInTouchMode(true);
		mBuildLevelView.setOnTouchListener(this);  

		try {
			Intent i = getIntent();

			String levelXML = i.getStringExtra("levelXML");

			mBuildLevelView.loadLevel(LocalContent.convertXML(levelXML));
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Notification that something is about to happen, to give the Activity a
	 * chance to save state.
	 * 
	 * @param outState a Bundle into which this Activity should save its state
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// just have the View's thread save its state into our Bundle
		super.onSaveInstanceState(outState);
	}

	public boolean onTouch(View v, MotionEvent event) {

		int action = event.getAction();

		if(action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE)
			mBuildLevelView.handleTouch((int) event.getX(), (int) event.getY());

		return true;
	}

	private void saveLevel() {

		try {
			mBuildLevelView.getLevel().setup(false);
			savePromptDialog("Save", "Level Name");
		}
		catch(Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();

			e.printStackTrace();
		}
	}

	private void uploadLeveL() {

		try {
			mBuildLevelView.getLevel().setup(false);
			uploadPromptDialog("Upload", "Level Name");
		}
		catch(Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();

			e.printStackTrace();
		}		
	}

	private void launchLevelSelect() {

		Intent intent = new Intent(this, LevelSelect.class);

		intent.putExtra("mode", "Load");

		startActivityForResult(intent, 1);
	}

	private void launchTest() {

		Level level = mBuildLevelView.getLevel();

		try {

			level.setup(false);

			Intent intent = new Intent(this, MrBall.class);

			intent.putExtra("mode", "Single");
			
			intent.putExtra("levelXML", level.toString());
			
			startActivity(intent);
		}
		catch(Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();

			e.printStackTrace();
		}

	}

	private void savePromptDialog(String title, String message) throws Exception{

//		AlertDialog.Builder alert = new AlertDialog.Builder(this);
//		alert.setTitle(title);
//		alert.setMessage(message);
//
//		// Set an EditText view to get user input
//		final EditText input = new EditText(this);
//		
//		// Check if the level already has a name
//		if(!mBuildLevelView.getLevel().getName().equals("Blank Level"))
//			input.setText(mBuildLevelView.getLevel().getName());
//		
//		alert.setView(input);
//
//		class Approve implements DialogInterface.OnClickListener{
//			private Level toSave;
//
//			public Approve(Level mlevel){
//				toSave = mlevel;
//			}
//
//			public void onClick(DialogInterface dialog, int which) {
//
//				String name = input.getText().toString();
//				if(name.equals(""))
//					return;
//				toSave.setName(name);
//				toSave.setCreator(GameManagement.get_playerID());
//				try{
//					GameManagement.save_Level(toSave,true);
//
//				}catch(Exception e){
//				}
//			}
//
//		}
//
//		alert.setPositiveButton("Ok",new Approve(mBuildLevelView.getLevel()));
//
//		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//			public void onClick(DialogInterface dialog, int whichButton) {
//
//			}
//		});
//
//		alert.show();
	}

	private void uploadPromptDialog(String title, String message) throws Exception{

//		AlertDialog.Builder alert = new AlertDialog.Builder(this);
//		alert.setTitle(title);
//		alert.setMessage(message);
//
//		// Set an EditText view to get user input
//		final EditText input = new EditText(this);
//		input.setText(mBuildLevelView.getLevel().getName());
//		alert.setView(input);
//
//		class Approve implements DialogInterface.OnClickListener{
//			private Level toSave;
//
//			public Approve(Level mlevel){
//				toSave = mlevel;
//			}
//
//			public void onClick(DialogInterface dialog, int which) {
//
//				String name = input.getText().toString();
//				if(name.equals(""))
//					return;
//				toSave.setName(name);
//				toSave.setCreator(GameManagement.get_playerID());
//				try{
//					GameManagement.upload_Level(toSave);
//
//				}catch(Exception e){
//				}
//			}
//
//		}
//
//		alert.setPositiveButton("Ok",new Approve(mBuildLevelView.getLevel()));
//
//		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//			public void onClick(DialogInterface dialog, int whichButton) {
//
//			}
//		});
//
//		alert.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode==RESULT_OK && requestCode==1){
			
			try {
				
				String levelXML = data.getStringExtra("levelXML");

				mBuildLevelView.loadLevel(LocalContent.convertXML(levelXML));
			}
			catch(Exception e) {
				e.printStackTrace();
			}
			
		}
	}
}